import { baseURL } from '@/api/_client.ts';
import { getMicroFileAPI } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useMicroFileStore = defineStore('MicroFileStore', () => {
  const microFileData = ref<any[]>([]);
  const loading = ref<boolean>(false);
  const microFilePage = ref({
    currentPage: 1,
    total: 0,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
  });

  const updateMicroFileData = async () => {
    loading.value = true;
    const req = {
      pageNo: microFilePage.value.currentPage,
      pageSize: microFilePage.value.pageSize,
    };

    const res = await getMicroFileAPI(req);
    const { data, meta } = res;

    microFileData.value = data.map((item: any) => ({
      id: item.id,
      title: item.attributes.title,
      videoUrl: baseURL + item.attributes.video?.data?.attributes?.url,
      date: item.attributes.time,
      information: item.attributes.information,
    }));
    microFilePage.value.total = meta.pagination.total;
    loading.value = false;
  };

  // 设置分页信息
  const setMicroFilePage = (page?: number) => {
    if (page) microFilePage.value.currentPage = page;
  };

  const getMicroFileData = computed(() => {
    return microFileData.value;
  });

  const getMicroFilePage = computed(() => {
    return microFilePage.value;
  });

  const pagination = computed(() => ({
    current: microFilePage.value.currentPage,
    total: microFilePage.value.total,
    pageSize: microFilePage.value.pageSize,
    onChange: (page: number) => {
      setMicroFilePage(page);
      updateMicroFileData().then();
    },
  }));

  const getMicroFileLoading = computed(() => {
    return loading.value;
  });

  return {
    updateMicroFileData,
    getMicroFileData,
    microFilePage,
    setMicroFilePage,
    getMicroFilePage,
    pagination,
    getMicroFileLoading,
  };
});
